# -*- coding:utf-8 -*-
import os, models, service, datetime, time
from pyExcelerator import Workbook

def getUnfinishedCasesExcelPath(branchCompanyId):
    filename = createFilename(branchCompanyId, models.Case.STATE_FINISHED)
    outputDir = getOutputDir()
    fullPathName = os.path.join(outputDir, filename)
    if not os.path.exists(fullPathName): #or (os.path.exists(fullPathName) and (getFileModifyName(fullPathName) >= models.Case.getLastestOperateTime())):
        cases = service.Case.getUnfinishedFormatCases(branchCompanyId)
        writeExcelFile(fullPathName, [[case.type, case.insurance_time, case.address, case.assessor, case.status, case.stay_days] for case in cases])
    return fullPathName

def getFinishedCasesExcelPath(branchCompanyId):
    filename = createFilename(branchCompanyId, models.Case.STATE_FINISHED)
    outputDir = getOutputDir()
    fullPathName = os.path.join(outputDir, filename)
    if not os.path.exists(fullPathName):# or (os.path.exists(fullPathName)): #and (getFileModifyName(fullPathName) >= models.Case.getLastestOperateTime())):
        cases = service.Case.getFinishedFormatCases(branchCompanyId)
        writeExcelFile(fullPathName, [[case.type, case.insurance_time, case.address, case.value, case.assessor, case.end_time] for case in cases])
    return fullPathName

def getFileModifyName(fullPathName):
    return datetime.datetime.fromtimestamp(os.path.getmtime(fullPathName))

def createFilename(branchCompanyId, status = 0):
    if models.Case.STATE_FINISHED == status:
        return 'report_%d_finished%d.xls' % (branchCompanyId, time.time())
    return 'report_%d_unfinished%d.xls' % (branchCompanyId, time.time())

def getOutputDir():
    ROOT = os.path.dirname(os.path.abspath(__file__))
    ROOT = os.path.dirname(ROOT)
    outputDir = os.path.join(ROOT, 'temp', str(os.getppid()))
    if not os.path.exists(outputDir):
        os.makedirs(outputDir)
    return outputDir

def writeExcelFile(fullPathName, table):
    wb = Workbook()
    ws = wb.add_sheet('Sheet1')
    for i, line in enumerate(table):
        for j, item in enumerate(line):
            ws.write(i, j, item)
    wb.save(fullPathName)


